package com.yuwei.module_repair

import android.app.AlertDialog
import android.content.DialogInterface
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.ContextThemeWrapper
import android.view.GestureDetector
import android.view.Gravity
import android.view.MotionEvent
import android.widget.PopupMenu
import androidx.activity.viewModels
import androidx.annotation.RequiresApi
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.bw.lib_base.path.RouterPath
import com.bw.lib_common.entity.RepairEntityItem
import com.bw.lib_common.view.BaseMvvmActivity
import com.bw.module_repair.adapter.RepairAdapter
import com.yuwei.module_repair.databinding.ActivityRepairManagerBinding
import com.yuwei.module_repair.viewmodel.RepairViewModel
/**
 * 智慧园区-06-物业报修V1.1-20250507-崔志彪
 */
@Route(path = RouterPath.MODULE_REPAIR_ACTIVITY)
class RepairManagerActivity : BaseMvvmActivity<ActivityRepairManagerBinding>() {
    lateinit var repairAdapter: RepairAdapter
    private val viewModel: RepairViewModel by viewModels()
    private val repairList = mutableListOf<RepairEntityItem>()


    @RequiresApi(Build.VERSION_CODES.M)
    override fun initViews() {
        super.initViews()
        binding.repairBack.setOnClickListener {
            finish()
        }
        binding.floating.setOnClickListener {
            ARouter.getInstance().build(RouterPath.MODULE_ADD_REPAIR_ACTIVITY).navigation()
        }
        repairAdapter = RepairAdapter()
        binding.repairRv.adapter = repairAdapter
        binding.repairRv.layoutManager= LinearLayoutManager(this)
        viewModel.getRepairList()
        val detector=GestureDetector(this@RepairManagerActivity,object : GestureDetector.SimpleOnGestureListener(){
            override fun onLongPress(e: MotionEvent) {
                super.onLongPress(e)
                val childView=binding.repairRv.findChildViewUnder(e.x,e.y)
                val position=binding.repairRv.getChildAdapterPosition(childView!!)
                val id=repairAdapter.data[position].id
                AlertDialog.Builder(this@RepairManagerActivity)
                    .setTitle("是否删除维修订单?")
                    .setPositiveButton("确定",object : DialogInterface.OnClickListener{
                        override fun onClick(p0: DialogInterface?, p1: Int) {
                            viewModel.deleteRepair(id)
                        }
                    })
                    .setNegativeButton("取消",null)
                    .show()
            }
        })
        binding.repairRv.addOnItemTouchListener(object : RecyclerView.OnItemTouchListener{
            override fun onInterceptTouchEvent(rv: RecyclerView, e: MotionEvent): Boolean {
                return detector.onTouchEvent(e)
            }

            override fun onTouchEvent(rv: RecyclerView, e: MotionEvent) {}

            override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {}
        })
        binding.llSort.setOnClickListener {
            AlertDialog.Builder(this)
                .setTitle("维修列表排序")
//                .setMessage("请按需进行排序")
                .setItems(arrayOf("升序","降序"),object : DialogInterface.OnClickListener{
                    override fun onClick(p0: DialogInterface?, p1: Int) {
                        when(p1){
                            0->{
                                //升序
                                repairAdapter.data.sortBy { it.id }
                                repairAdapter.notifyDataSetChanged()
                                binding.ivSort.setImageResource(R.drawable.ic_sort_up)
                                binding.tvSort.setText("升序")
                            }
                            1->{
                                //降序
                                repairAdapter.data.sortByDescending { it.id }
                                repairAdapter.notifyDataSetChanged()
                                binding.ivSort.setImageResource(R.drawable.ic_sort_down)
                                binding.tvSort.setText("降序")
                            }
                        }
                    }
                })
                .setNegativeButton("取消",null)
                .show()
        }
        binding.etSearch.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {}

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                viewModel.getRepairOrderByName(p0.toString())
            }

            override fun afterTextChanged(p0: Editable?) {

            }
        })
        binding.ivSearch.setOnClickListener {
            viewModel.getRepairOrderByOrderNumber(binding.etSearch.text.toString())
        }
        val wrapper =
            ContextThemeWrapper(this, com.bw.lib_common.R.style.CustomPopupMenu)
        val popupMenu = PopupMenu(wrapper, binding.llFilter)
        popupMenu.menuInflater.inflate(R.menu.status_menu, popupMenu.menu)
        popupMenu.gravity = Gravity.BOTTOM
        binding.llFilter.setOnClickListener {
            popupMenu.show()
        }
        popupMenu.setOnMenuItemClickListener {
            repairAdapter.data.clear()
            title = it.title.toString()
            val list = repairList.filter {
                it.processingStatus == title
            }
            repairAdapter.data.addAll(list)
            repairAdapter.notifyDataSetChanged()
            false
        }
    }
    override fun observeDataChange() {
        viewModel.getRepairListSuccess.observe(this){
            repairList.addAll(it)
            repairAdapter.data.clear()
            repairAdapter.data.addAll(it)
            repairAdapter.notifyDataSetChanged()
        }
        viewModel.deleteRepairSuccess.observe(this){
            ToastUtils.showLong("删除成功")
            viewModel.getRepairList()
        }
        viewModel.getRepairOrderByNumberSuccess.observe(this){
            repairAdapter.data.clear()
            repairAdapter.data.add(it)
            repairAdapter.notifyDataSetChanged()
        }
        viewModel.getRepairOrderByNameSuccess.observe(this){
            repairAdapter.data.clear()
            repairAdapter.data.addAll(it)
            repairAdapter.notifyDataSetChanged()
        }
    }

    override fun getLayoutId(): Int =R.layout.activity_repair_manager

    override fun onResume() {
        super.onResume()
        viewModel.getRepairList()
    }
}